package com.jiexin.util;

import com.jiexin.common.ConfigDatasource;
import com.jiexin.model.Mail;
import lombok.extern.slf4j.Slf4j;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

@Slf4j
@Component
public class ExchangeMailUtil {

    public static boolean send(Mail mail, ConfigDatasource configDatasource) {

        String from = configDatasource.getConfig("mailAccount");
        String host = configDatasource.getConfig("mailHost");
        String pass = configDatasource.getConfig("mailPassword");
        try {
            ExchangeClient client = new ExchangeClient.ExchangeClientBuilder()
                    .hostname(host)
                    .exchangeVersion(ExchangeVersion.Exchange2010)
                    .username(from)
                    .password(pass)
                    .recipientTo(new ArrayList<>(mail.getReceivers()))
                    .subject(mail.getSubject())
                    .message(mail.getMessage())
                    .build();
            client.sendExchange();
            log.info("{} 发送邮件到 {}", from, StringUtils.join(mail.getReceivers(), ","));
            return true;
        } catch (Exception e) {
            log.error(from + "发送邮件到" + StringUtils.join(mail.getReceivers(), ",") + "失败", e);
            return false;
        }
    }

}
